package com.web.controller;

import com.domain.Employee;
import com.service.EmployeeService;
import com.service.PermissionService;
import com.util.JsonResult;
import com.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author shkstart
 * @create 2022/3/14-17:22
 */
@Controller
public class LoginController {

    @Autowired
    private EmployeeService service;
    @Autowired
    private PermissionService permissionService;

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username,String password, HttpSession session){
        try {
            Employee employee = service.login(username, password);
            //把员工放到session中
            //session.setAttribute(UserContext.EMP_IN_SESSION,employee);
            UserContext.setCurrentUser(employee);

            //判断是否是超级管理员，如果不是就查询
            if(! employee.isAdmin()){
                //根据登录用户id查询员工拥有的权限表达式列表，存到session中
                List<String> expressions = permissionService.selectByEmpId(employee.getId());
                //session.setAttribute(UserContext.USER_EXPRESSIONS_IN_SESSION,expressions);
                UserContext.setExpression(expressions);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"操作失败");
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        //销毁会话
        session.invalidate();
        return "redirect:/login.html";
    }
}
